package com.bainuo.doctor.common.widget.datapicker;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;


import com.bainuo.doctor.common.R;
import com.bainuo.doctor.common.widget.wheelview.OnWheelChangedListener;
import com.bainuo.doctor.common.widget.wheelview.OnWheelScrollListener;
import com.bainuo.doctor.common.widget.wheelview.WheelView;
import com.bainuo.doctor.common.widget.wheelview.adapter.AbstractWheelTextAdapter;
import com.blankj.utilcode.utils.LogUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * 出生日期选择对话框
 * 
 * @author 
 *
 */
public class SelectDatePopup extends PopupWindow implements View.OnClickListener {

	private Context context;


	private View vChangeBirth;
	private View vChangeBirthChild;
	private TextView btnSure;
	private TextView btnCancel;

	private ArrayList<String> arry_years = new ArrayList<String>();
	private ArrayList<String> arry_months = new ArrayList<String>();
	private ArrayList<String> arry_days = new ArrayList<String>();
	private ArrayList<String> arry_hour = new ArrayList<String>();
	private ArrayList<String> arry_min = new ArrayList<String>();



	final int MAX_ITEMS = 5;
	CalendarTextAdapter[] adapters = new CalendarTextAdapter[MAX_ITEMS];
	WheelView[] wheelViews = new WheelView[MAX_ITEMS];
	int[] currentVaules = new int[MAX_ITEMS];


	private int baseYear;
	private boolean issetdata = false;
	private int daysInMonth;


	enum ITEM_INDEX{
		ITEM_YEAR,
		ITEM_MONTH,
		ITEM_DAY,
		ITEM_HOUR,
		ITEM_MIN,
	}

	private OnBirthListener onBirthListener;

	static SelectDatePopup show(Context context,View view){
		SelectDatePopup popWindow = new SelectDatePopup(context);
		popWindow.showPopWindow(view);
		return popWindow;
	}


	View mView;
	public SelectDatePopup(Context context) {
		super(context);
		this.context = context;

		Calendar c = Calendar.getInstance();
		baseYear = c.get(Calendar.YEAR);
//		initView();
	}
	private void initView(){
		mView = LayoutInflater.from(context).inflate(R.layout.dialog_changebirth,null);


		int[] ids = new int[]{
				R.id.wv_birth_year,
				R.id.wv_birth_month,
				R.id.wv_birth_day,
				R.id.wv_birth_hour,
				R.id.wv_birth_min
		};

		final ArrayList<String>[] datas = new ArrayList[]{
				arry_years,
				arry_months,
				arry_days,
				arry_hour,
				arry_min
		};

		initData();

		OnWheelChangedListener changedListener = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub

				int seletIndex = 0;
				for (int i=0;i<wheelViews.length;i++){
					if (wheel == wheelViews[i]){
						currentVaules[i] = wheel.getCurrentItem();
						seletIndex = i;
						break;
					}
				}

				if (seletIndex != ITEM_INDEX.ITEM_YEAR.ordinal()
						&& seletIndex != ITEM_INDEX.ITEM_MONTH.ordinal())
					return;

				int days = getDaysInMonth();
				if (days != daysInMonth){

					initDays(days);
					int index = ITEM_INDEX.ITEM_DAY.ordinal();
					WheelView wheelView = wheelViews[index];
					if (currentVaules[index] > days-1){
						currentVaules[index] = days-1;
					}

					adapters[index] = new CalendarTextAdapter(wheelView,context,
							datas[index],
							currentVaules[index],
							18,
							14);
					wheelView.setViewAdapter(adapters[index]);
					wheelView.setCurrentItem(currentVaules[index]);
				}
			}
		};


		for (int i=0;i<MAX_ITEMS;i++){

			WheelView wheelView =(WheelView) mView.findViewById(ids[i]);
			adapters[i] = new CalendarTextAdapter(wheelView,context,
					datas[i],
					currentVaules[i],
					18,
					14);

			wheelView.setVisibleItems(6);
			wheelView.setViewAdapter(adapters[i]);
			wheelView.setCurrentItem(currentVaules[i]);
			wheelView.addChangingListener(changedListener);
			wheelViews[i] = wheelView;
		}

		vChangeBirth = mView.findViewById(R.id.ly_myinfo_changebirth);
		vChangeBirthChild = mView.findViewById(R.id.ly_myinfo_changebirth_child);
		btnSure = (TextView) mView.findViewById(R.id.selectdate_tv_ok);
		btnCancel = (TextView) mView.findViewById(R.id.selectdate_tv_cancel);

		vChangeBirth.setOnClickListener(this);
		vChangeBirthChild.setOnClickListener(this);
		btnSure.setOnClickListener(this);
		btnCancel.setOnClickListener(this);



		this.setContentView(mView);// 设置View
		this.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);// 设置弹出窗口的宽
		this.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);// 设置弹出窗口的高
		this.setFocusable(true);// 设置弹出窗口可
		// 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
		this.setBackgroundDrawable(new ColorDrawable());
	}


	public void showPopWindow(View view) {
		initView();
		this.showAtLocation(view, Gravity.BOTTOM , 0, 0);
	}

	public void initDays(int days) {

		daysInMonth = days;

		arry_days.clear();
		for (int i = 1; i <= daysInMonth; i++) {
			arry_days.add(String.format("%d日",i));
		}
	}

	private class CalendarTextAdapter extends AbstractWheelTextAdapter {
		ArrayList<String> list;

		WheelView wheelView;
		protected CalendarTextAdapter(WheelView wheelView,Context context, ArrayList<String> list, int currentItem, int maxsize, int minsize) {
			super(context, R.layout.gp_item_birth_year, NO_RESOURCE, currentItem, maxsize, minsize);
			this.list = list;
			this.wheelView = wheelView;
			setItemTextResource(R.id.tempValue);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			View view = super.getItem(index, cachedView, parent);
			return view;
		}

		@Override
		public int getItemsCount() {
			return list.size();
		}

		@Override
		protected CharSequence getItemText(int index) {
			return list.get(index) + "";
		}
	}

	public void setBirthdayListener(OnBirthListener onBirthListener) {
		this.onBirthListener = onBirthListener;
	}

	@Override
	public void onClick(View v) {

		if (v == btnSure) {
			if (onBirthListener != null) {
				currentVaules[ITEM_INDEX.ITEM_YEAR.ordinal()]+=baseYear;
				currentVaules[ITEM_INDEX.ITEM_MONTH.ordinal()]+=1;
				currentVaules[ITEM_INDEX.ITEM_DAY.ordinal()]+=1;
				onBirthListener.onClick(currentVaules);
			}
		}
//		else if (v == btnCancel) {
//			dismiss();
//		}
		else if (v == vChangeBirthChild) {
			return;
		} else {
			dismiss();
		}
		dismiss();

	}

	public interface OnBirthListener {
		public void onClick(int value[]);
	}



	public void initData() {

		Calendar c = Calendar.getInstance();

		if (!issetdata) {
			currentVaules[ITEM_INDEX.ITEM_YEAR.ordinal()] = 0;
			currentVaules[ITEM_INDEX.ITEM_MONTH.ordinal()]  = c.get(Calendar.MONTH);
			currentVaules[ITEM_INDEX.ITEM_DAY.ordinal()]  = c.get(Calendar.DATE)-1;
			currentVaules[ITEM_INDEX.ITEM_HOUR.ordinal()]  = c.get(Calendar.HOUR_OF_DAY);
			currentVaules[ITEM_INDEX.ITEM_MIN.ordinal()]  = c.get(Calendar.MINUTE);
		}



		for (int i = baseYear; i < baseYear+100; i++) {
			arry_years.add(i + "年");
		}

		arry_months.clear();
		for (int i = 1; i <= 12; i++) {
			arry_months.add(i + "月");
		}

		initDays(getDaysInMonth());

		arry_hour.clear();
		for (int i = 0; i < 24; i++) {
			arry_hour.add(String.format("%02d时",i));
		}

		arry_min.clear();
		for (int i = 0; i < 60; i++) {
			arry_min.add(String.format("%02d分",i));
		}

	}

	/**
	 * 设置年月日
	 * 
	 * @param year
	 * @param month
	 * @param day
	 */
	public void setDate(int year, int month, int day,int hour,int min) {

		issetdata = true;
		int[] data = new int[]{
				year-baseYear,month,day-1,hour,min
		};

		for (int i=0;i<currentVaules.length;i++)
			currentVaules[i] = data[i];
	}


	int[] dayVaules = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
	/**
	 * 计算每月多少天
	 *
	 */
	public int getDaysInMonth() {

		int year = currentVaules[ITEM_INDEX.ITEM_YEAR.ordinal()]+baseYear;
		int month = currentVaules[ITEM_INDEX.ITEM_MONTH.ordinal()];

		if(month == 1 && year % 4 == 0 && year % 100 != 0) {
			return 29;
		}
		return dayVaules[month];
	}
}